package com.sukumar.android.backit.activity;

import java.util.regex.Pattern;

import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPrefPassword;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.sukumar.android.backit.R;

public class BackItPreferenceActivity extends PreferenceActivity {
	ListPreference emailprovider;
	EditTextPreference emailAddress;
	EditTextPrefPassword emailPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.sms_preference);

		final Pattern EMAIL_ADDRESS_PATTERN = Pattern
				.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
						+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
						+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+");

		CheckBoxPreference sendBgEmail = (CheckBoxPreference) findPreference(getText(R.string.direct_email_key));

		emailprovider = (ListPreference) findPreference(getText(R.string.email_provider_key));
		emailAddress = (EditTextPreference) findPreference(getText(R.string.email_address_key));
		emailPassword = (EditTextPrefPassword) findPreference(getText(R.string.email_password_key));

		Preference usagePref = (Preference) findPreference(getText(R.string.Usage_btn));
		Preference changeLogPref = (Preference) findPreference(getText(R.string.Changelog_btn));
		Preference aboutPref = (Preference) findPreference(getText(R.string.About));
		Preference rulePref = (Preference) findPreference(getText(R.string.rule_add_key));

		setDefaultValue();
		if (!validateSMSInbox()) {
			CheckBoxPreference smsInboxDelete = (CheckBoxPreference) findPreference(getText(R.string.del_sms_inbox_key));
			smsInboxDelete.setChecked(false);
			smsInboxDelete.setEnabled(false);
			smsInboxDelete
					.setSummary("Your phone does not support deletion of messages from inbox");
		}
		sendBgEmail
				.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						Boolean newBoolValue = (Boolean) newValue;
						if (newBoolValue == true) {
							emailprovider.setEnabled(true);
							emailAddress.setEnabled(true);
							emailPassword.setEnabled(true);
						} else {
							Editor prefEditor = PreferenceManager
									.getDefaultSharedPreferences(
											getApplicationContext()).edit();
							prefEditor.remove(getText(
									R.string.email_provider_key).toString());
							prefEditor.remove(getText(
									R.string.email_address_key).toString());
							prefEditor.remove(getText(
									R.string.email_password_key).toString());
							emailprovider.setEnabled(false);
							emailAddress.setEnabled(false);
							emailPassword.setEnabled(false);
							prefEditor.commit();
						}
						return true;

					}
				});

		emailAddress
				.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
					@Override
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						boolean validEmail = EMAIL_ADDRESS_PATTERN.matcher(
								newValue.toString()).matches();
						if (validEmail) {
							return true;
						} else {
							Toast.makeText(
									getApplicationContext(),
									"Invalid email address: "
											+ newValue.toString(),
									Toast.LENGTH_SHORT).show();
							return false;
						}
					}
				});

		usagePref
				.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
					@Override
					public boolean onPreferenceClick(Preference paramPreference) {
						Intent myIntent = new Intent(getApplicationContext(),
								BackItAboutActivity.class);
						myIntent.putExtra("selected", paramPreference.getKey());
						startActivity(myIntent);
						return true;
					}
				});

		changeLogPref
				.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
					@Override
					public boolean onPreferenceClick(Preference paramPreference) {
						Intent myIntent = new Intent(getApplicationContext(),
								BackItAboutActivity.class);
						myIntent.putExtra("selected", paramPreference.getKey());
						startActivity(myIntent);
						return true;
					}
				});

		aboutPref
				.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
					@Override
					public boolean onPreferenceClick(Preference paramPreference) {
						Intent myIntent = new Intent(getApplicationContext(),
								BackItAboutActivity.class);
						myIntent.putExtra("selected", paramPreference.getKey());
						startActivity(myIntent);
						return true;
					}
				});

		rulePref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference paramPreference) {
				Intent myIntent = new Intent(getApplicationContext(),
						BackItRuleListActivity.class);
				myIntent.putExtra("selected", paramPreference.getKey());
				startActivity(myIntent);
				return true;
			}
		});
	}

	private boolean validateSMSInbox() {
		boolean valid = true;
		final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
		String WHERE_CONDITION = "body like '%BING%'";
		String SORT_ORDER = "date DESC";
		Cursor cur = null;
		try {
			 cur = getContentResolver().query(SMS_INBOX,
					new String[] { "address", "body" }, WHERE_CONDITION, null,
					SORT_ORDER);

			if (cur.getCount() > 0) {
				if (cur.moveToFirst()) {
					do {
						cur.getString(0);
						cur.getString(1);
					} while (cur.moveToNext());
				}
			}
		} catch (Exception e) {
			valid = false;
		}finally{
			cur.close();
		}
		return valid;
	}

	private void setDefaultValue() {
		CheckBoxPreference sendBgEmail = (CheckBoxPreference) findPreference(getText(R.string.direct_email_key));

		if (sendBgEmail.isChecked()) {
			emailprovider.setEnabled(true);
			emailAddress.setEnabled(true);
			emailPassword.setEnabled(true);
		} else {
			emailprovider.setEnabled(false);
			emailAddress.setEnabled(false);
			emailPassword.setEnabled(false);
		}

	}
}
